package com.jiangyg.mall.authz.service.impl;

import com.jiangyg.mall.authz.service.MemberUserDetailsService;
import com.jiangyg.mall.authz.support.authentication.member.MemberUserDetails;
import com.jiangyg.mall.authz.support.authentication.exception.UnknowException;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.member.vo.MemberAuthzInfoVO;
import com.jiangyg.mall.member.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 类描述：会员用户信息查询实现
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-01-05
 */
@Slf4j
@Service
public class MemberUserDetailsServiceImpl implements MemberUserDetailsService {

    @Reference
    private MemberService memberService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // TODO 追加 Dubbo 权限校验
            MemberAuthzInfoVO member = memberService.selectAuthzInfoByAccount(username);
            if (member == null) {
                throw new UsernameNotFoundException("账户不存在！");
            }
            return new MemberUserDetails(member);
        } catch (AuthenticationException ex) {
            throw ex;
        } catch (Exception ex) {
            // TODO 待测试下 skywalking 不跑异常只输出error异常是否能采集
            final String errMsg = String.format("会员用户[%s]登录出现未知异常，", username);
            Logger.error(log, () -> errMsg, ex);
            throw new UnknowException(errMsg, ex);
        }
    }

}
